<template>
  <div class="api-con">
    <div class="left-con">
      <div class="search-con">
        <Input
          v-model="key"
          placeholder="请输入关键字..."
          style="width: 50%"
          clearable
          @on-enter="handleSearchApi"
        />
        <Button type="primary" @click="handleSearchApi">搜索</Button>
        <Checkbox v-model="showAll">查看全部</Checkbox>
      </div>
      <div class="list-con">
        <div v-show="!showAll">
          <div
            class="list-item"
            :class="{ active: curApi.id === item.id }"
            v-for="item in curApis"
            :key="item.id"
            @click="handleClick(item)"
          >
            <div
              class="label"
              :style="{
                color: colorMap[item.method],
              }"
            >
              {{ item.method }}
            </div>
            <div class="info">
              <div class="title">
                {{ item.title }}
              </div>
              <div class="url">
                {{ item.url
                }}<span style="float: right">{{ item.node_name }}</span>
              </div>
            </div>
          </div>
        </div>
        <Tree
          :data="apiData"
          show-checkbox
          v-show="showAll"
          @on-check-change="handleCheckChange"
          @on-select-change="handleClick"
        ></Tree>
      </div>
    </div>

    <div class="api-detail">
      <div class="header">
        <span
          :style="{
            fontSize: '1rem',
            paddingRight: '.5rem',
            color: colorMap[curApi.method],
          }"
          >{{ curApi.method }}</span
        >
        <Input :value="curApi.url" style="width: 60%"> </Input>
        <Button type="primary" @click="getResponse">发送请求</Button>
      </div>
      <div class="body">
        <div class="detail-item">
          <div class="title">参数</div>
          <div class="json-con" ref="paramCon"></div>
        </div>
        <div class="detail-item">
          <div class="title">结果</div>
          <div class="json-con" ref="resultCon"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jsoneditor from "jsoneditor";
import { commonApi, getAllApis } from "@/api";
// import { setGlobalData } from "@/initMicroApps";
import store from "@/store";

export default {
  props: {
    curPathProp: {
      type: String,
    },
  },
  data() {
    return {
      key: "",
      showAll: false,
      curApi: {},
      allApis: [],
      apiData: [],
      paramEditor: null,
      resultEditor: null,
      colorMap: {
        GET: "#19be6b",
        POST: "#2d8cf0",
        DELETE: "#ed4014",
        PUT: "#ff9900",
      },
      curApis: [],
    };
  },
  watch: {
    curPathProp(path) {
      console.log(path);
      this.showAll = false;
      this.getCurApis(path);
    },
  },
  mounted() {
    const options = {
      mode: "code",
      modes: ["code", "text", "tree", "preview"],
    };
    getAllApis().then((res) => {
      this.allApis = res;

      this.getCurApis();
    });
    this.paramEditor = new jsoneditor(this.$refs.paramCon, options);
    this.resultEditor = new jsoneditor(this.$refs.resultCon, options);
  },
  methods: {
    async handleCheckChange(data) {
      let path = this.curPathProp;
      if (!path) return;
      data = data.filter((data) => data.node_name);
      let ids = data.map((data) => data.id);
      let res = await commonApi({
        method: "post",
        url: "/system/set/apis/:id",
        data: {
          ids,
          path,
        },
        title: "关联api",
        response: [],
      });
      if (!res.error) {
        this.$Message.success("关联成功！");
        this.getCurApis();
      }
    },
    async getCurApis() {
      let path = this.curPathProp;
      if (!this.curPathProp) return;
      let res = await commonApi({
        method: "get",
        url: "/system/getCurApiIdsByPath/:path",
        data: {
          path,
        },
        title: "获取当前系统关联的api",
        response: [
        
        ],
      });
      res = res ? res : [];
      this.curApis = res.map((item) => {
        return {
          ...item,
          response: item.response ? JSON.parse(item.response) : {},
        };
      });

      store.commit("SET_CURAPIS", this.curApis);
      // setGlobalData({ curApis: this.curApis });
      let ids = res.map((item) => item.id);
      let fullData = JSON.parse(JSON.stringify(this.allApis));

      fullData.forEach((item) => {
        if (item.children) {
          item.expand = false;
          item.children.forEach((item2) => {
            if (ids.includes(item2.id)) {
              item2.checked = true;
              item.expand = true;
            } else {
              item2.checked = false;
            }
          });
        }
      });

      this.handleSearchApi(fullData);
    },

    async getResponse() {
      let data = this.paramEditor.get();
      let info = {
        ...this.curApi,
        data,
      };
      let res = await commonApi(info);
      if (res.error) {
        this.$Message.error("接口调用失败，请检查参数！");
        return;
      }
      if (typeof res === "object" && res != null) {
        this.resultEditor.set(res);
      } else {
        this.resultEditor.set({ res });
      }
      if (res !== null && !this.curApi.response) {
        commonApi({
          method: "PUT",
          url: "/interface/:id",
          data: {
            id: this.curApi.id,
            response: JSON.stringify(res),
          },
          title: "更新结果",
          response: {},
        });
      }
    },
    handleSearchApi(fullData) {
      if (!this.key) {
        this.apiData = fullData;
        return;
      }
      let res = [];
      fullData.forEach((item) => {
        let obj = {
          ...item,
          children: [],
        };
        if (item.children.length) {
          item.children.forEach((item2) => {
            if (item2.title.includes(this.key)) {
              obj.children.push(item2);
            }
          });
        }
        if (obj.title.includes(this.key) || obj.children.length) {
          res.push(obj);
        }
      });
      this.apiData = res;
    },

    async handleClick(item) {
      if (item[0] && !item[0].node_name) {
        return;
      }
      this.curApi = item[0] ? item[0] : item;
      let res = await commonApi({
        method: "GET",
        url: "/interface/getDetailById/:id",
        data: {
          id: this.curApi.id,
        },
        title: "根据id获取api详细信息",
        response: {},
      });
      if (res.data) {
        let params = {};
        let origionParam = JSON.parse(res.data);
        Object.keys(origionParam).forEach((key) => {
          let value;
          let type;
          let param = origionParam[key];
          if (param instanceof Array) {
            param = param[0];
          }
          type = param.type ? param.type : param;
          switch (type) {
            case "string":
              value = "";
              break;
            case "number":
              value = param.min ? param.min : 0;
              break;
            case "array":
              value = [];
              break;
            case "object":
              value = {};
              break;
            default:
              value = "";
              break;
          }
          params[key] = value;
        });
        this.paramEditor.set(params);
      } else {
        this.paramEditor.set({});
      }
      if (res.response) {
        this.resultEditor.set(JSON.parse(res.response));
      } else {
        this.resultEditor.set({});
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.api-con {
  width: 100%;
  height: 100%;
  display: flex;
  .left-con {
    width: 30rem;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #dcdee2;
    .search-con {
      padding: 1rem 0;
      text-align: center;
      border-bottom: 1px solid #dcdee2;
    }
    .list-con {
      flex: 1;
      overflow: auto;
      .list-item {
        padding: 0.5rem;
        display: flex;
        border-bottom: 1px solid #dcdee2;
        cursor: pointer;
        .label {
          font-size: 1rem;
          padding: 0.5rem;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 5rem;
        }
        .info {
          flex: 1;
          padding-left: 0.5rem;
          font-size: 1rem;
        }
      }
      .list-item:hover {
        background: #ecf4fa;
        color: #1890ff;
      }
      .list-item.active {
        background: #ecf4fa;
        color: #1890ff;
      }
      .ivu-tree {
        padding-left: 1rem;
      }
    }
  }

  .api-detail {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    .header {
      height: 3rem;
      border-bottom: 1px solid #dcdee2;
      text-align: center;
      line-height: 3rem;
      padding: 0;
    }
    .body {
      flex: 1;
      display: flex;
      padding: 0.5rem;
      .detail-item {
        flex: 1;
        height: 100%;
        display: flex;
        flex-direction: column;
        padding: 0.5rem;
        .title {
          line-height: 2rem;
          height: 2rem;
          font-size: 1rem;
          font-weight: bold;
        }
        .json-con {
          flex: 1;
        }
      }
    }
  }
}
</style>
